package cn.kennylee.codehub.springmvc.exceptionhandler;

import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.core.Ordered;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * <p> SQL 异常处理类 </p>
 * <p>Created on 2025/7/21.</p>
 *
 * @author kennylee
 * @since 0.0.1
 */
@RestControllerAdvice
@ConditionalOnClass(name = "org.springframework.jdbc.BadSqlGrammarException")
@Slf4j
public class SqlExceptionHandler implements Ordered {

    private final ExceptionResultFactory resultFactory;

    public SqlExceptionHandler(ExceptionResultFactory resultFactory) {
        this.resultFactory = resultFactory;
    }

    @PostConstruct
    public void init() {
        log.info("SQL异常处理类已初始化");
    }

    @ExceptionHandler(BadSqlGrammarException.class)
    public ResultModel<Object> handleBadSqlGrammarException(BadSqlGrammarException e) {
        log.error("SQL语法错误", e);
        String errorMessage = "数据库操作失败";
        errorMessage += ": " + e.getSql();
        if (e.getSQLException() != null) {
            errorMessage += " (" + e.getSQLException().getMessage() + ")";
        }
        return resultFactory.createFailedResult(ResultErrorCode.SQL_ERROR, errorMessage);
    }

    @Override
    public int getOrder() {
        return 3;
    }
}
